<template>
  <!-- Excel -->
  <div ref="containerRef" class="univer-container" />
</template>

<script setup lang="ts">
import "@univerjs/design/lib/index.css";
import "@univerjs/ui/lib/index.css";
import "@univerjs/docs-ui/lib/index.css";
import "@univerjs/sheets-ui/lib/index.css";
import "@univerjs/sheets-formula/lib/index.css";

import { Univer, LocaleType, UniverInstanceType, Tools } from "@univerjs/core";
import { defaultTheme } from "@univerjs/design";
import { UniverDocsPlugin } from "@univerjs/docs";
import { UniverDocsUIPlugin } from "@univerjs/docs-ui";
import { UniverFormulaEnginePlugin } from "@univerjs/engine-formula";
import { UniverRenderEnginePlugin } from "@univerjs/engine-render";
import { UniverSheetsPlugin } from "@univerjs/sheets";
import { UniverSheetsFormulaPlugin } from "@univerjs/sheets-formula";
import { UniverSheetsUIPlugin } from "@univerjs/sheets-ui";
import { UniverUIPlugin } from "@univerjs/ui";
import { FUniver } from "@univerjs/facade";
import { onBeforeUnmount, onMounted, ref } from "vue";

import DesignZhCN from "@univerjs/design/lib/locale/zh-CN";
import UIZhCN from "@univerjs/ui/lib/locale/zh-CN";
import DocsUIZhCN from "@univerjs/docs-ui/lib/locale/zh-CN";
import SheetsZhCN from "@univerjs/sheets/lib/locale/zh-CN";
import SheetsUIZhCN from "@univerjs/sheets-ui/lib/locale/zh-CN";

const { data } = defineProps({
  // workbook data
  data: {
    type: Object,
    default: () => ({}),
  },
});

const univerRef = ref<Univer | null>(null);
const containerRef = ref<HTMLElement | null>(null);

onMounted(() => {
  const univer = new Univer({
    theme: defaultTheme,
    locales: {
      [LocaleType.ZH_CN]: Tools.deepMerge(
        SheetsZhCN,
        DocsUIZhCN,
        SheetsUIZhCN,
        UIZhCN,
        DesignZhCN
      ),
    },
  });
  univerRef.value = univer;

  // core plugins
  univer.registerPlugin(UniverRenderEnginePlugin);
  univer.registerPlugin(UniverFormulaEnginePlugin);
  univer.registerPlugin(UniverUIPlugin, {
    container: containerRef.value!,
    header: true,
    toolbar: true,
    footer: true,
  });

  // doc plugins
  univer.registerPlugin(UniverDocsPlugin, {
    hasScroll: false,
  });

  // doc ui plugins
  univer.registerPlugin(UniverDocsUIPlugin);

  // sheet plugins
  univer.registerPlugin(UniverSheetsPlugin);
  univer.registerPlugin(UniverSheetsUIPlugin);
  univer.registerPlugin(UniverSheetsFormulaPlugin);

  // create workbook instance
  univer.createUnit(UniverInstanceType.UNIVER_SHEET, data);
});

// Destroy univer instance and workbook instance
onBeforeUnmount(() => {
  univerRef.value?.dispose();
  univerRef.value = null;
});

const getData = () => {
  const univerAPI = FUniver.newAPI(univerRef.value);
  const savedData = univerAPI.getActiveWorkbook()?.getSnapshot();
  return savedData;
};

defineExpose({
  getData,
});
</script>

<style scoped>
.univer-container {
  width: 100%;
  height: 100%;
  overflow: hidden;
}

:global(.univer-menubar) {
  display: none;
}
</style>
